#include <bits/stdc++.h>

using namespace std;

typedef long long ll;

#define in read()

int read(){
	int x = 0,sgn = 1;char ch = getchar();
	for(;!isdigit(ch);ch = getchar()) if(ch == '-') sgn = -1;
	for(;isdigit(ch);ch = getchar()) x = (x<<1)+(x<<3)+(ch^48);
	return x*sgn;
}

const int MAXN = 1e5+10;
const int inf = 0x3f3f3f3f;

int n,h[MAXN],cnt,dep[MAXN],ans,dmin[MAXN],dmax[MAXN],f[MAXN];
struct tree{int l,r;}t[MAXN];
bool to[MAXN];

void dfs(int x){
	if(t[x].l == -1 || t[x].r == -1) dmin[x] = dmax[x] = dep[x] + 1;
	if(t[x].l == -1 && ~t[x].r){
		dep[t[x].r] = dep[x] + 1; dfs(t[x].r); dmin[x] = min(dmin[x],dmin[t[x].r]); dmax[x] = max(dmax[x],dmax[t[x].r]);
		if(dmax[x] - dmin[x] > 1) {ans = -1;return;} f[x] = 1;
	}else if(t[x].r == -1 && ~t[x].l){
		dep[t[x].l] = dep[x] + 1; dfs(t[x].l); dmin[x] = min(dmin[x],dmin[t[x].l]); dmax[x] = max(dmax[x],dmax[t[x].l]);
		if(dmax[x] - dmin[x] > 1) {ans = -1;return;} f[x] = 0;
	}else if(~t[x].l && ~t[x].r){
		dep[t[x].l] = dep[x] + 1; dep[t[x].r] = dep[x] + 1; dfs(t[x].l); dfs(t[x].r);
		dmin[x] = min(dmin[t[x].l],dmin[t[x].r]);
		dmax[x] = max(dmax[t[x].l],dmax[t[x].r]); if(dmax[x] - dmin[x] > 1){ans = -1; return;}
		if(dmax[t[x].l] - dmin[t[x].l] >= 1 && dmax[t[x].r] - dmin[t[x].r] >= 1) {ans = -1;return;}
		if(dmax[t[x].l] - dmin[t[x].l] >= 1 && dmax[t[x].r] == dmin[t[x].r]){
			if(dmin[t[x].l] < dmin[t[x].r]) f[x] = f[t[x].l] + 1;
			else f[x] = f[t[x].l];
		}
		if(dmax[t[x].r] - dmin[t[x].r] >= 1 && dmax[t[x].l] == dmin[t[x].l]){
			if(dmin[t[x].r] < dmin[t[x].l]) f[x] = f[t[x].r];
			else f[x] = f[t[x].r] + 1;
		}
		if(dmax[t[x].r] == dmin[t[x].r] && dmax[t[x].l] == dmin[t[x].l]){
			f[x] = dmin[t[x].r] > dmin[t[x].l];
		}		
	}
}

int main (){
	n = in;for(int i = 1;i <= n;i++){t[i].l = in;t[i].r = in; if(~t[i].l) to[t[i].l] = 1;if(~t[i].r) to[t[i].r] = 1;}
	int root = 0;for(int i = 1;i <= n;i++) if(!to[i]) {root = i;break;}
	memset(dmin,0x3f,sizeof(dmin));
	dfs(root);
	if(ans == -1 || f[root] >= inf) puts("-1");
	else printf("%d\n",f[root]);
	return 0;
}

